package com.txzt.gaea.common.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageUtil {

    /**
     * 裁剪图片白边部分（ 对需获取白色部门不适用 ）
     * @param sourceUrl
     * @param targetUrl
     * @throws IOException
     */
    public static void cutImage(String sourceUrl, String targetUrl) throws IOException {
        BufferedImage image = ImageIO.read(new File(sourceUrl));
        int top = 0;
        int left = 0;
        int bottom = image.getHeight();
        int right = image.getWidth();

        for (int i = 0; i < image.getHeight(); i++) {
            boolean find = false;
            for (int j = 0; j < image.getWidth(); j++) {
                int pixel = image.getRGB(j, i);
                if (!isWhite(pixel)) {
                    top = i;
                    find = true;
                    break;
                }
            }
            if (find) {
                break;
            }
        }

        for (int i = 0; i < image.getWidth(); i++) {
            boolean find = false;
            for (int j = top; j < image.getHeight(); j++) {
                int pixel = image.getRGB(i, j);
                if (!isWhite(pixel)) {
                    left = i;
                    find = true;
                    break;
                }
            }
            if (find) {
                break;
            }
        }

        for (int i = image.getHeight() - 1; i >= 0; i--) {
            boolean find = false;
            for (int j = left; j < image.getWidth(); j++) {
                int pixel = image.getRGB(j, i);
                if (!isWhite(pixel)) {
                    bottom = i;
                    find = true;
                    break;
                }
            }
            if (find) {
                break;
            }
        }

        for (int i = image.getWidth() - 1; i >= 0; i--) {
            boolean find = false;
            for (int j = 0; j <= bottom; j++) {
                int pixel = image.getRGB(i, j);
                if (!isWhite(pixel)) {
                    right = i;
                    find = true;
                    break;
                }
            }
            if (find) {
                break;
            }
        }
        BufferedImage target = image.getSubimage(left, top, right - left, bottom - top);
        ImageIO.write(target, "jpg", new File("/Users/fangcong/Documents/temp/test/test.jpg"));

    }

    /**
     * 判断是否白色（10点误差）
     * @param pixel
     * @return
     */
    private static boolean isWhite(int pixel) {
        int[] rgb = new int[3];
        rgb[0] = (pixel & 0xff0000) >> 16; //r
        rgb[1] = (pixel & 0xff00) >> 8; //g
        rgb[2] = (pixel & 0xff);//b
        //RGB 都为255 为纯白
        return rgb[0] > 245 && rgb[1] > 245 && rgb[2] > 245;
    }
}
